package com.saa.common.filter;


import com.alibaba.fastjson2.JSONObject;
import com.saa.common.utils.CommonUtil;
import com.saa.system.po.SaaApiLog;
import com.saa.system.service.SaaSysLogService;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

public class SessionFilter implements Filter {

	private String excludedPages;
	private String[] excludedPageArray;
	RestTemplate restTemplate;
	//@Autowired
	//private JwtTokenUtil jwtTokenUtil;

	//@Autowired
	//private FilterPowerService filterPowerService;

	//@Autowired
	//private ConfigdefineService configdefineService;

	@Value("${jwt.header}")
	private final String jwtHeader="Authorization";

	@Value("${jwt.tokenHead}")
	private final String jwtTokenHead = "Arch6WithCloud ";
	@Value("${session.loginUrl}")
	private final String sessionLoginUrl = "http://portal-sso.nocar-portal.svc.cluster.local:3001/api/user?token=";

	private String ssoLoginUrl;

	private String callbackUrl;

	private String caTokenUrl;

	private String ignorePatterns;

	private Logger LOGGER = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private SaaSysLogService saaSysLogService;


	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		//TODO 需要在权限完成后进行改造
		HttpServletResponse res = (HttpServletResponse) response;
		HttpServletRequest req = (HttpServletRequest) request;
		MDC.put("traceId", UUID.randomUUID().toString());
		/*
		放开对应接口请求
		/getCheckData					查勘报告数据内容的封装
		/getLossesApprovalData			损失核定清单数据内容的封装
		/getCalculationSheetData		计算书数据内容的封装
		/getSettleReportData   			结案报告数据内容的封装
		/getPrepayCalculateReportData	预付计算书数据内容的封装
		 */
		if (req.getRequestURI().endsWith("auth") || req.getRequestURI().endsWith("loginSSO") ||
				req.getRequestURI().endsWith("getCheckData") || req.getRequestURI().endsWith("getLossesApprovalData") ||
				req.getRequestURI().endsWith("getCalculationSheetData") || req.getRequestURI().endsWith("getSettleReportData") ||
				req.getRequestURI().endsWith("getPrepayCalculateReportData")|| req.getRequestURI().endsWith("autoEndClaim") ||
				req.getRequestURI().endsWith("claimPushInfo") || req.getRequestURI().endsWith("uploadDocument")|| req.getRequestURI().endsWith("updatePrpLPayee")
				|| req.getRequestURI().endsWith("findRegistHistory") || req.getRequestURI().endsWith("queryPayStatus") || req.getRequestURI().endsWith("queryCodeList")
				|| req.getRequestURI().endsWith("queryComCodeSqlParam")) {
			filterChain.doFilter(request, response);
		} else {
			BodyReaderRequestWrapper bodyReaderRequestWrapper = new BodyReaderRequestWrapper(req);
			String requestBody = bodyReaderRequestWrapper.getRequestBody();
			String requestURL = req.getRequestURL().toString();
			if(requestURL.indexOf("/saa/login")>0){
				Map<String,Object> body = JSONObject.parseObject(requestBody,Map.class);
				/***登录日志**/
				SaaApiLog saaSysLog = new SaaApiLog();
				saaSysLog.setId(CommonUtil.getUpperUuid());
				UserAgent userAgent = UserAgent.parseUserAgentString(req.getHeader("user-agent"));
				String clientType = userAgent.getOperatingSystem().getDeviceType().toString();//客户端类型  手机、电脑、平板
				String browserVersion = userAgent.getBrowserVersion()==null?"":userAgent.getBrowserVersion().getVersion();//浏览器类型
				String os = userAgent.getOperatingSystem().getName();//操作系统类型
				String ip = this.getIpAddr(req); //请求ip
				saaSysLog.setLogType("7");//登录
				saaSysLog.setOperatingSystem(os);
				saaSysLog.setIp(ip);
				saaSysLog.setBrowser(browserVersion);
				saaSysLog.setCreateBy(body.get("userCode").toString());
				saaSysLog.setCreateTime(new Date());
				saaSysLog.setMac("");
				saaSysLog.setPort("");
				saaSysLog.setRequestText(requestBody);
				saaSysLog.setUpdateBy(body.get("userCode").toString());
				saaSysLog.setUpdateTime(new Date());
				saaSysLog.setUrl("/saa/login");
				saaSysLog.setUserCode(body.get("userCode").toString());
				saaSysLog.setValid("1");
				saaSysLogService.saveSaaApiLog(saaSysLog);
			}
			filterChain.doFilter(bodyReaderRequestWrapper, response);
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		excludedPages = config.getInitParameter("excludedPages");
		if (StringUtils.isNotEmpty(excludedPages)) {
			excludedPageArray = excludedPages.split(",");
		}
		ServletContext sc = config.getServletContext();
		WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(sc);
		if(cxt!=null){
			/*if(interfPowerService==null){
				interfPowerService = cxt.getBean(InterfPowerService.class);
			}*/
		}
		return;
	}

	private void unauthorized(ServletRequest request,ServletResponse response,String code) throws IOException {

		HttpServletResponse res = (HttpServletResponse) response;
		res.setContentType("application/json;charset=utf-8");
		rewriteHeader(request,response);

		res.setHeader("praga", "no-cache");
		res.setHeader("cache-control", "no-cache");
		res.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, Access-Toke");
		PrintWriter writer = res.getWriter();
		writer.write("{\"status\":\"300\",\"message\":\"未登录\",\"data\":{\"code\":\""+code+"\"}}");
	}

	private void rewriteHeader(ServletRequest request,ServletResponse response){
		HttpServletResponse res = (HttpServletResponse) response;
		HttpServletRequest req = (HttpServletRequest)request;
		String agent=req.getHeader("User-Agent").toLowerCase();
		String accept = req.getHeader("accept").toLowerCase();
		if((agent.indexOf("msie")>0 || agent.indexOf("gecko")>0) && accept.contains("text/html")){//如果是IE浏览器
			res.setContentType("text/html;charset=utf-8");
		}
	}

	//其中ip的获取方式
	public static String getIpAddr(HttpServletRequest request) {

		String ip = request.getHeader("x-forwarded-for");

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
			//LOGGER.error("X-Real-IP:"+ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("http_client_ip");
//            LOGGER.error("http_client_ip:"+ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
//            LOGGER.error("getRemoteAddr:"+ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
//            LOGGER.error("Proxy-Client-IP:"+ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
//            LOGGER.error("WL-Proxy-Client-IP:"+ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
//            LOGGER.error("HTTP_X_FORWARDED_FOR:"+ip);
		}
		// 如果是多级代理，那么取第一个ip为客户ip
		if (ip != null && ip.indexOf(",") != -1) {
			ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
			//            LOGGER.error("ip:"+ip);
		}
		return ip;
	}

}
